// 计数器：判断线程池的任务是否已经全部执行完

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class CountDownLatchDemo1 {
    public static void main(String[] args) throws InterruptedException {
        // 创建计数器
        CountDownLatch countDownLatch = new CountDownLatch(5);
        // 创建新线程执行任务
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                Thread currThread = Thread.currentThread();
                System.out.println(currThread.getName() + "开始执行");
                // 线程执行所用时间
                int runTime = (1 + new Random().nextInt(5));
                try {
                    TimeUnit.SECONDS.sleep(runTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(currThread.getName() + "执行完成，用时" + runTime);
                //计数器-1
                countDownLatch.countDown();
            },"线程" + i+"-> ").start();
        }
        countDownLatch.await(); // 阻塞等待，直到所有线程执行完
        System.out.println("执行结果");
    }
}
